# coding:utf8

from sqlalchemy.sql import func
from appserver import db_store
from datetime import datetime
from sqlalchemy.orm import relationship,backref
from sqlalchemy import or_
from models.entity.tree_model_base import TreeModelBase
"""
岗位表
"""


class Quarter(TreeModelBase):
    __tablename__ = "quarters"
    __bind_key__ = "main"
    # 在链接过程中对应的值为2
    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    code = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u'岗位编号')
    name = db_store.Column(db_store.String(64), nullable=False, comment=u'岗位名称')
    description = db_store.Column(db_store.String(255), nullable=False, comment=u"描述")
    parent_id = db_store.Column(db_store.Integer, nullable=False,default=0,comment=u"父id")
    path = db_store.Column(db_store.String(64), unique=True, comment=u'岗位路径')
    dis_order = db_store.Column(db_store.Integer, default=0)
    department_id = db_store.Column(db_store.Integer, db_store.ForeignKey('departments.id'), nullable=False, comment=u'部门id')
    # department_id = db_store.Column(db_store.Integer, nullable=False, comment=u'部门id')
    create_time = db_store.Column(db_store.Date, nullable=False, default=datetime.now())
    # creater_id = db_store.Column(db_store.Integer, db_store.ForeignKey('users.id'), nullable=False)
    depth =  db_store.Column(db_store.Integer, default=1)  # 职位深度
    status = db_store.Column(db_store.Integer, nullable=False, comment="岗位状态")  # 0-无效 1-有效
    # Department = relationship("Department", backref=backref('quarters', order_by=id))

    def __repr__(self):
        return "<Quarter %s %s>" % (self.name,self.code)

    @staticmethod
    def get_quarter_by_name(self,name):
        quarter = Quarter.query.filter_by(name=name).first()
        return quarter

    @staticmethod
    def get_quarter_by_id(id_num):
        # 根据id得到模块
        return Quarter.query.filter_by(id=id_num).first()

    @staticmethod
    def get_all_quarters():
        # 得到所有模块的列表
        return Quarter.query.all()

    @staticmethod
    def get_all_quarters_by_department_id(department_id):
        # 得到所有模块的列表
        return Quarter.query.filter_by(department_id=department_id).all()

    @staticmethod
    def get_quarter_by_path(path):
        quarters= Quarter.query.filter_by(Quarter.path.like(path+",*")).all
        return quarters

    def add(self,name, code, description, dis_order, department_id, parent_id,creater_id):
        data=[]
        tmp = {}


    def edit(self,name, description, code, dis_order, parent_id, department_id,create_time,status):
        tmp={}
        data= []
        # if code != self.code and Quarter.query.filter_by(code=code).first():
        if code!= self.code and Quarter.query.filter_by(code=code).first():
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "编码存在"
            tmp['data'] = data
            return tmp
        # 如果修改了部门编号，就需要重新进行判断
        if self.department_id != department_id:  # 1 , 2
            # 该部门有了名称相同的岗位，修改失败
            if Quarter.query.filter_by(name=name).filter_by(department_id=department_id).first():
                tmp['success'] = 0
                tmp['error_code'] = -1
                tmp['error_msg'] = "该部门有了该岗位，请重新设置"
                tmp['data'] = data
                return tmp
            else:
                # 修改quarter对应的属性
                # 当岗位的部门已经改变,当下所有节点向上升一级
                self.department_id = department_id
                self.parent_id = parent_id
                self.path = Quarter.get_quarter_by_id(parent_id).first().path + str("id")
                self.save()
                quarters = Quarter.get_all_quarters()
                quarters.remove(self)
                for item in quarters:
                    item_path = item.path.spilit(',')
                    if self.id in item_path:
                        item_path.remove(self.id)
                        if len(item_path)>1:
                            item.q_quarter = item_path[-2]
                        else:
                            item.q_quarter = 0
                        item.save(item)
        # 如果没有改变department-id的时候
        else:
            # 如果该节点加入了自己的子节点
            # 得到要插入的节点
            if self.parent_id != 0:
                old_quarter = Quarter.query.filter_by(id=self.parent_id).first()
                if str(self.id) in old_quarter.path.split(","):
                    tmp = {}
                    tmp['success'] = 0
                    tmp['error_code'] = -2
                    tmp['error_msg'] = '禁止将节点自身移动到自身下'
                    return tmp
                old_quarter.child_num -= 1
                db_store.session.add(old_quarter)
                relative_depth = self.depth - old_quarter.depth  # 计算相对深度
            else:
                relative_depth = self.depth
            # 处理新的父节点
            if parent_id != 0:
                new_p_quarter = Quarter.query.filter_by(id=parent_id).first()
                new_p_quarter.child_num += 1
                db_store.session.add(new_p_quarter)
                self.depth = new_p_quarter.depth + 1
                self.path = new_p_quarter.path + "," + str(self.id)  # 更改自身路径
            else:
                self.depth = 1
                self.path = str(self.id)
            # 处理自身的父子关系
            self.parent_id = parent_id
            # 处理自身的子节点的父子关系
            all_child_nodes = Quarter.query.filter(
                Quarter.path.like(self.path + "%")).all()  # 根据自身路径获取所有的子节点
            all_child_nodes.remove(self)  # 将自身移除出列表
            for child_node in all_child_nodes:
                child_node_path_list = child_node.path.split(",")
                keep_list = child_node_path_list[(child_node.depth - 1):]
                change_list = self.path.split(",")
                child_node.path = ",".join(change_list + keep_list)  # 生成child_node的path
                child_node.depth = self.depth + relative_depth  # 生成child_node的depth
                db_store.session.add(child_node)
            if self.save():
                tmp['success'] = 1
                tmp['error_code'] = None
                tmp['error_msg'] = None
                tmp['data'] = data
                return tmp
            else:
                tmp['success'] = 0
                tmp['error_code'] = -1
                tmp['error_msg'] = "未知错误"
                tmp['data'] = data
                return tmp
    
    @staticmethod
    def get_quarter_dic(the_quarter):
        rdic={}
        '''
        name":"董事长的长工",
        "description":"让别人活的",
        "code":"JCP2240dt",
        "dis_order":2,
        "create_time": 2018-8-28
        "department_id":3,
        "parent_id":1
        "status":1
        '''
        rdic["id"]=the_quarter.id
        rdic["name"]=the_quarter.name
        rdic["description"]=the_quarter.description
        rdic["parent_id"]=the_quarter.parent_id
        rdic["create_time"]=the_quarter.create_time.strftime("%Y-%m-%d")
        rdic["code"] = the_quarter.code
        rdic["dis_order"] = the_quarter.dis_order
        rdic["department_id"] = the_quarter.department_id
        rdic["status"] = the_quarter.status
        return rdic
    
    @staticmethod
    def search(query_word):
            search_list=Quarter.query.filter(or_(Quarter.name.like("%"+query_word+"%"),Quarter.code.like("%"+query_word+"%"),
                                                                        Quarter.description.like("%"+query_word+"%"))).all()
            tlist=[]
            for item in search_list:
                tlist.append(Quarter.get_quarter_dic(item))
            rdic={
                            "success":1,
                            "error_code":None,
                            "error_msg":None,
                            "data":tlist
                    }
            return rdic
